package com.cloud.code.牛客网;

import java.util.ArrayList;
import java.util.Comparator;

class Interval {
    int start;
    int end;

    Interval() {
        start = 0;
        end = 0;
    }

    Interval(int s, int e) {
        start = s;
        end = e;
    }
}

public class Test74 {

    public static void main(String[] args) {

    }

    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        ArrayList<Interval> res = new ArrayList<>();
        if (intervals.size() <= 0) {
            return res;
        }
        if (intervals.size() == 1) {
            return intervals;
        }

        intervals.sort(new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                return o1.start - o2.start;
            }
        });


        Interval tem = intervals.get(0);
        for (int i = 1; i < intervals.size(); i++) {
            if (tem.end >= intervals.get(i).start) {
                int endt = tem.end > intervals.get(i).end ? tem.end : intervals.get(i).end;
                tem = new Interval(tem.start, endt);
            } else {
                res.add(tem);
                tem = intervals.get(i);
            }
            if (i == intervals.size() - 1) {
                res.add(tem);
            }
        }
        return res;

    }
}
